package com.codeos.khttp.request.body;

import com.codeos.khttp.utils.KHttpUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class KBodyItemText implements KBodyItem {


    private StringBuffer mHttpHeader = new StringBuffer();
    private String mText;

    public KBodyItemText(String name, String text, String properties) {
        if(text == null) {
            throw new IllegalArgumentException("please set text!");
        }

        mText = text;

        if(name == null) {
            name = "text";
        }

        if(properties == null) {
            mHttpHeader.append("Content-Disposition: form-data; name=\""+name+"\";"+ KHttpUtils.gHttpEnd);
        } else {
            mHttpHeader.append("Content-Disposition: form-data; name=\""+name+"\"; "+properties+";" + KHttpUtils.gHttpEnd);
        }
        mHttpHeader.append("Content-Type: text/plain" + KHttpUtils.gHttpEnd);

        mHttpHeader.append(KHttpUtils.gHttpEnd);
    }

    @Override
    public int getItemLength() {
        // mText.getBytes().length 如果直接 mText.length()会忽略中文，导致长度不正确
        return mHttpHeader.length() + mText.getBytes().length + KHttpUtils.gHttpEnd.length();
    }

    @Override
    public void sendItemData(OutputStream os, OutputStreamWriter writer) throws IOException {

        writer.write(mHttpHeader.toString());
        writer.write(mText+ KHttpUtils.gHttpEnd);
        writer.flush();

    }

    @Override
    public String toString() {
        return mHttpHeader.toString()+"[Text] "+mText+KHttpUtils.gHttpEnd;
    }
}
